<?php

namespace addons\yiliao\controller\api;

use fast\Http;
use think\Validate;
use think\Db;
use fast\Random;
use app\admin\model\yiliao\Useropenid;
use app\admin\model\yiliao\Usercoupon;
use app\admin\model\yiliao\Bookmark;
use app\admin\model\yiliao\Code;
use app\admin\model\yiliao\Log as LogModel;
use app\admin\model\yiliao\User as UserModel;
use EasyWeChat\Factory;

class User extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function myinvitelog()
    {
        $ret = [];
        $ret['num'] = UserModel::where(['parentid'=>$this->user['userid']])->count();
        $jifen = LogModel::where(['yiliao_user_id'=>$this->user['userid'],'type'=>1])->sum('point');
        $ret['jifen']=$jifen;
        $rows =  LogModel::where(['yiliao_user_id'=>$this->user['userid'],'type'=>1])->order("id desc")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['time']=date("Y-m-d H:i:s", $v['createtime']);
        }
        $ret['rows'] = $rows;
        $this->success('', $ret);
    }
    public function myinvite()
    {
        $rows = UserModel::where(['parentid'=>$this->user['userid']])->order("id desc")->field("id,createtime,nickname,avatar")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['time'] = date("Y-m-d H:i:s", $v['createtime']);
            $rows[$k]['avatar'] = cdnurl($v['avatar'], true);
        }
        $this->success('', $rows);
    }
    public function haibao()
    {
        $isminapp = $this->request->param('isminapp');
        $ret = [];
        $data = UserModel::where(['id'=>$this->user['userid']])->find();
        $ret['userid'] =$this->user['userid'];
        $ret['name']=$data['nickname'];
        if ($isminapp==1) {
            //生成二维码
            ///www/wwwroot/xx/public
            $document_path = request()->server('DOCUMENT_ROOT');
            $path = '/uploads/yiliao/'.md5($this->user['userid']).'.jpg';
            if (!file_exists($document_path.$path)) {
                $access = $this->getaccess();
                $api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access['access_token'];
                $can = [];
                $can['page']='pages/index/index';
                $can['scene']="parentid=".$this->user['userid'];
                $can['check_path']=false;
                $can['auto_color']=false;
                $can['width']=430;
                //$can['env_version']='develop';
                $res = Http::post($api, json_encode($can));

                if (!is_dir($document_path.'/uploads/yiliao')) {
                    mkdir(iconv("UTF-8", "GBK", $document_path.'/uploads/yiliao'), 0777, true);
                }
                $file = fopen($document_path.$path, "w");//创建件准备写入
                fwrite($file, $res);//写入
                fclose($file);//关闭
            }
            $ret['ewm']=$this->apiurl.$path;
        } else {
            $ret['ewm']=$this->apiurl."?parentid=".$this->user['userid'];
        }
        $this->success('', $ret);
    }
    public function userCenter()
    {
        $ret=[];
        $ret['coupon']=Usercoupon::where(['userid'=>$this->user['userid'],'status'=>'hidden'])->count();
        $ret['bookmark']=Bookmark::where(['yiliao_user_id'=>$this->user['userid']])->count();
        $this->success('', $ret);
    }

    public function getPhoneNumber()
    {
        $code = $this->request->param('code');
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');
        $parentid = $this->request->param('parentid');

        $config = [
            'app_id' => $this->setting['appid'],
            'secret' => $this->setting['appsecret'],
        
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        $app = Factory::miniProgram($config);
        $userinfo=$app->auth->session($code);
        if (array_key_exists('openid', $userinfo)) {
            $decryptedData = $app->encryptor->decryptData($userinfo['session_key'], $iv, $encryptedData);
            if (array_key_exists('phoneNumber', $decryptedData)) {
                $mobile = $decryptedData['phoneNumber'];
                $user = UserModel::where(['username'=>$mobile])->find();
                $useropenid = Useropenid::where(['id'=>$this->user['id']])->find();
                if (!$user) {
                    $d=[];
                    if ($parentid>0) {
                        $setting = $this->setting;
                        $parent = UserModel::where(['id'=>$parentid])->find();
                        $fenxiao1 = intval($setting['fenxiao1']*$setting['yqfen']/100);
                        $fenxiao2 = $setting['yqfen']-$fenxiao1;
                        //送积分
                        $log=[];
                        $log['createtime']=time();
                        $log['yiliao_user_id']=$parentid;
                        $log['name']="邀请好友送积分".$parentid;
                        $log['point']=$fenxiao1;
                        $total = $fenxiao1+$parent['jifen'];
                        $log['total']=$total;
                        $log['type']=1;
                        Log::insert($log);
                        UserModel::where(['id'=>$parentid])->update(['jifen'=>$total]);
                        if ($parent['parentid']>0 && $fenxiao2>0) {
                            $parent = UserModel::where(['id'=>$parent['parentid']])->find();
                            //送积分
                            $log=[];
                            $log['createtime']=time();
                            $log['yiliao_user_id']=$parent['parentid'];
                            $log['name']="邀请好友送积分".$parent['parentid'];
                            $log['point']=$fenxiao2;
                            $total = $fenxiao2+$parent['jifen'];
                            $log['total']=$total;
                            $log['type']=1;
                            Log::insert($log);
                            UserModel::where(['id'=>$parent['parentid']])->update(['jifen'=>$total]);
                        }
                    }
                    $d['parentid'] = $parentid;
                    $d['createtime'] =time();
                    $d['updatetime']=time();
                    $d['username']=$mobile;
                    $d['coupon_num']=0;
                    $d['status']='normal';
                    $d['nickname']=Random::alpha(6);
                    $res = UserModel::insert($d);
                    if ($res) {
                        $id = UserModel::getLastInsID();
                        if ($useropenid['userid']==0) {
                            Useropenid::where(['openid'=>$this->user['openid']])->update(['userid'=>$id]);
                            Db::commit();
                            $this->success("登录成功");
                        } else {
                            $this->error('已经绑定过');
                        }
                    } else {
                        $this->error("登录失败");
                    }
                } elseif ($useropenid['userid']==0) {
                    Useropenid::where(['openid'=>$this->user['openid']])->update(['userid'=>$user['id']]);
                    Db::commit();
                    $this->success("登录成功");
                }
            }
        } else {
            $this->error('获取失败');
        }
    }
    /**
     * 公众号获取用户信息
     */
    public function openid()
    {
        $setting = $this->setting;
        $code = $this->request->param("code");
       
        $api="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$setting['gzhappid']."&secret=".$setting['gzhsecret']."&code=".$code."&grant_type=authorization_code";
        $res = Http::post($api);
        $json = json_decode($res, true);
        
        if (isset($json['access_token'])) {
            $access_token = $json['access_token'];
            $refresh_token = $json['refresh_token'];
            $openid = $json['openid'];
            //$unionid = $json['unionid'];
           // $api='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid;
           // $res = Http::get($api);
           // $json = json_decode($res,true);
            //$nickname = $json['nickname'];
            //$avatar = $json['headimgurl'];
            /**
             * Array ( [openid] => opgg26XVDQqettirruPtek0fCokY [nickname] => 福娃 [sex] => 0 [language] => [city] => [province] => [country] => [headimgurl] => https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJHDDXcRWdxnibcGVnH1LtXcE9zIYjQOQfqYQg3EktKibIXTkcCsywWRxYxyeiac1MulibfkX84hiaC1bA/132 [privilege] => Array ( ) )
            */
            if ($json && $json['openid']) {
                $user = Useropenid::where(['openid'=>$json['openid']])->find();
                $session_key=md5(Random::alnum(30));
                if ($user) {
                    Useropenid::where('openid', $json['openid'])->update(['session_key'=>$session_key]);
                    $this->success('success', ['sessionid'=>$session_key]);
                } else {
                    $d=[];
                    $d['createtime'] = time();
                    $d['updatetime'] = time();
                    $d['openid'] = $json['openid'];
                    $d['type']='gzh';
                    $d['userid']=0;
                    $d['session_key']=$session_key;
                    $res = Useropenid::insert($d);
                    if ($res) {
                        $this->success('success', ['sessionid'=>$session_key]);
                    } else {
                        $this->success('success', ['sessionid'=>'']);
                    }
                }
            } else {
                $this->success('success', ['sessionid'=>'']);
            }
        } else {
            $this->success('success', ['sessionid'=>'']);
        }
    }

    /**
     * 获取用户
     */
    public function getUser()
    {
        //是否返回配置参数
        $ext  = $this->request->param('ext', 0);
        $user = $this->user;
        if ($user) {
            unset($user['openid']);
            if ($user['userid'] > 0) {
                $data = UserModel::where(['id'=>$user['userid']])->find();
                $user['mobile']=$data['username'];
                $user['islogin']=1;
                $user['desc']="欢迎登录";
                if ($data['avatar']) {
                    $user['avatar'] = cdnurl($data['avatar'], true);
                } else {
                    $user['avatar']="";
                }
                $user['avatarurl']=$data['avatar'];
                $user['nickname'] = $data['nickname'];
                $user['sex'] = $data['sex'];
                $user['birthday'] = $data['birthday'];
                $user['jifen']=$data['jifen'];
            } else {
                $user['mobile']="请登录";
                $user['islogin']=0;
                $user['desc']="";
                $user['avatar'] = "";
                $user['avatarurl']="";
                $user['nickname'] = "";
                $user['sex'] = "";
                $user['birthday'] = "";
                $user['jifen']=0;
            }
            
            $this->success('success', $user);
        } else {
            if ($ext==1) {
                $setting = $this->setting;
                $this->error("请先登录", ['gzhappid'=>$setting['gzhappid']]);
            } else {
                $this->error("请先登录");
            }
        }
    }

    /**
     * 微信小程序登录
     */
    public function login()
    {
        $setting = $this->setting;
        $code = $this->request->param("code", '');
        $parentid = $this->request->param("parentid", 0);
        $api = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$setting['appid']."&secret=".$setting['appsecret']."&js_code=".$code."&grant_type=authorization_code";
        $res = Http::post($api);
        $json = json_decode($res, true);
        
        if (isset($json['openid']) && $json['openid']) {
            $user = Useropenid::where('openid', $json['openid'])->find();
            if ($user) {
                Useropenid::where('openid', $json['openid'])->update(['session_key'=>$json['session_key']]);
                $this->success('success', ['sessionid'=>$json['session_key'], 'time'=>time()+7200]);
            } else {
                $d=[];
                $d['createtime'] = time();
                $d['updatetime'] = time();
                $d['openid'] = $json['openid'];
                //$d['name'] = Random::alnum(6);
                //$d['name'] ="";
                //$d['avatar'] = '';
                $d['session_key'] = $json['session_key'];
               
                $d['userid']=0;
                $d['type']="xcx";
                
                if ($json['openid']) {
                    Useropenid::insert($d);
                    $userid = Useropenid::getLastInsID();
                    $this->success('success', ['sessionid'=>$json['session_key'], 'time'=>time()+7200]);
                } else {
                    $this->success('success', ['sessionid'=>'']);
                }
            }
        } else {
            $this->success('success', ['sessionid'=>'']);
        }
    }

    /**
     * 发送短信验证码
     */
    public function sendcode()
    {
        $mobile = $this->request->param("mobile");
        $sms = $this->setting;
        $alisms = new \addons\yiliao\libs\Alisms(
            [
                'sms_key'=>$sms['smskey'],
                'sms_secret'=>$sms['smssecret'],
                'sms_sign'=>$sms['smssign'],
                'sms_tml_reg'=>$sms['smstpl']
            ]
        );
        
        $code = rand(1000, 9999);
        //删除两天前的短信记录
        Code::where(["createtime"=>["lt",time()-86400*2]])->delete();
        //统计今天发送次数
        $start = strtotime(date("Y-m-d").' 00:00:00');
        $end = strtotime(date("Y-m-d").' 23:59:59');
        $cishu=Code::where(['createtime'=>['between',[$start,$end]],'mobile'=>$mobile])->count();
        if ($cishu<$this->setting['smsnum']) {
            $res = $alisms->sendsms($mobile, array('code'=>$code));
            if ($res['Code'] == "OK") {
                $d=[];
                $d['createtime'] = time();
                $d['mobile'] = $mobile;
                $d['code']=$code;
                $d['exptime']=time()+600;
                $res = Code::insert($d);
                if ($res) {
                    $this->success("短信发送成功");
                } else {
                    $this->error("短信发送失败");
                }
            } else {
                $this->error("短信发送失败");
            }
        } else {
            $this->error("短信发送超限,请明天再试");
        }
        
    }

    public function mobileLogin()
    {
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $parentid = $this->request->param('parentid');
        Db::startTrans();
        try {
            $data = Code::where(['mobile'=>$mobile,'code'=>$code])->find();
            if ($data) {
                $user = UserModel::where(['username'=>$mobile])->find();
                $useropenid = Useropenid::where(['id'=>$this->user['id']])->find();
                if (!$user) {
                    $d=[];
                    if ($parentid>0) {
                        $setting = $this->setting;
                        $parent = UserModel::where(['id'=>$parentid])->find();
                        $fenxiao1 = intval($setting['fenxiao1']*$setting['yqfen']/100);
                        $fenxiao2 = $setting['yqfen']-$fenxiao1;
                        //送积分
                        $log=[];
                        $log['createtime']=time();
                        $log['yiliao_user_id']=$parentid;
                        $log['name']="邀请好友送积分".$parentid;
                        $log['point']=$fenxiao1;
                        $total = $fenxiao1+$parent['jifen'];
                        $log['total']=$total;
                        $log['type']=1;
                        LogModel::insert($log);
                        UserModel::where(['id'=>$parentid])->update(['jifen'=>$total]);
                        if ($parent['parentid']>0 && $fenxiao2>0) {
                            $parent = UserModel::where(['id'=>$parent['parentid']])->find();
                            //送积分
                            $log=[];
                            $log['createtime']=time();
                            $log['yiliao_user_id']=$parent['parentid'];
                            $log['name']="邀请好友送积分".$parent['parentid'];
                            $log['point']=$fenxiao2;
                            $total = $fenxiao2+$parent['jifen'];
                            $log['total']=$total;
                            $log['type']=1;
                            Log::insert($log);
                            UserModel::where(['id'=>$parent['parentid']])->update(['jifen'=>$total]);
                        }
                    }
                    $d['createtime'] =time();
                    $d['updatetime']=time();
                    $d['username']=$mobile;
                    $d['coupon_num']=0;
                    $d['parentid']=$parentid;
                    $d['status']='normal';
                    $d['nickname'] = Random::alpha(6);
                    $res = UserModel::insert($d);
                    if ($res) {
                        $id = UserModel::getLastInsID();
                        if ($useropenid['userid']==0) {
                            Useropenid::where(['openid'=>$this->user['openid']])->update(['userid'=>$id]);
                            Db::commit();
                            $this->success("登录成功");
                        } else {
                            $this->error('已经绑定过');
                        }
                    } else {
                        $this->error("登录失败");
                    }
                } elseif ($useropenid['userid']==0) {
                    Useropenid::where(['openid'=>$this->user['openid']])->update(['userid'=>$user['id']]);
                    Db::commit();
                    $this->success("登录成功");
                } else {
                    //$this->error();
                }
            } else {
                $this->error('验证码错误');
            }
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取优惠券
     */
    public function myCoupons()
    {
        $date = date("Y-m-d");
        $rows = Usercoupon::where(['status'=>'hidden', 'userid'=>$this->user['userid'], 'start'=>['elt',$date], 'end'=>['egt',$date]])->select();
        $ret=[];
        $ret[]=['id'=>0,'value'=>0,'name'=>'不使用优惠','checked'=>true];
        foreach ($rows as $v) {
            $ret[]=['id'=>$v['id'], 'value'=>$v['price'], 'name'=>$v['name'], 'checked'=>false];
        }
        $this->success('', $ret);
    }
}
